package com.sgb.kjwl.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.sgb.kjwl.R;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.InstallEvent;
import com.swgk.core.download.DownloadListner;
import com.swgk.core.download.DownloadManager;
import com.swgk.core.util.MLog;

import org.greenrobot.eventbus.EventBus;

import java.io.File;


/**
 * Created by WYJ on 2020-11-06.
 */
public class UpdateService extends Service {

    //定义notify的id，避免与其它的notification的处理冲突
    private final int NOTIFY_ID = 100;
    private final String UPDATE_CHANNEL_ID = "update_channel_id";
    private final String UPDATE_CHANNEL_NAME = "update_channel_name";
    private static NotificationManager notificationManager;
    private static NotificationCompat.Builder builder;
    private boolean isDownLoading;
    private float rate = .0f;
    DownloadManager mDownloadManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null){
            String url = TextUtils.isEmpty(intent.getStringExtra("url"))?"":intent.getStringExtra("url");
            String filePath = TextUtils.isEmpty(intent.getStringExtra("filePath"))?"":intent.getStringExtra("filePath");
            String fileName = TextUtils.isEmpty(intent.getStringExtra("fileName"))?"":intent.getStringExtra("fileName");
            if (!TextUtils.isEmpty(url) && !TextUtils.isEmpty(filePath) && !TextUtils.isEmpty(fileName) &&!isDownLoading) {
                isDownLoading = true;
                initDownloads(url, filePath, fileName);
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void initDownloads(String uri, String filePath, String fileName) {
        //创建下载任务管理器
        mDownloadManager = DownloadManager.getInstance();
        //将下载任务添加至任务管理器中，并创建下载线程
        mDownloadManager.add(uri, filePath, fileName, new DownloadListner() {
            private int load = 0;

            @Override
            public void onFinished() { //下载完成
                MLog.e("自动更新", "下载完成!");
                EventBus.getDefault().postSticky(InstallEvent.make(EventConstant.EVENT_INSTALL_APP, new File(filePath, fileName).getPath()));
                if (notificationManager != null) {
                    notificationManager.cancelAll();
                    notificationManager = null;
                }
                stopSelf();
            }

            @Override
            public void onProgress(float progress, boolean isDownloading) { //更新中
                MLog.e("自动更新", "更新中" + progress);
                if (isDownloading) { //当是下载时
                    int load = (int) Math.floor(progress * 100);
                    if (this.load != load || this.load == 0){
                        this.load = load;
                        initNotification(getApplicationContext(), load);
                    }
                } else { //当是读取进度时
                    String progressString = String.format("%.2f", progress * 100) + "%";
                    if ("100.00%".equals(progressString)) {
                        EventBus.getDefault().postSticky(InstallEvent.make(EventConstant.EVENT_INSTALL_APP, new File(filePath, fileName).getPath()));
                        if (notificationManager != null) {
                            notificationManager.cancelAll();
                            notificationManager = null;
                        }
                        stopSelf();
                    } else {
                        if (notificationManager == null) {
//                            initNotification(getApplicationContext(), (int) Math.floor(progress * 100));
                        } else {
                            downloadProgress((int) Math.floor(progress * 100));
                        }
                    }
                }
            }

            @Override
            public void onPause() { //暂停
                MLog.e("自动更新", "暂停了");
            }

            @Override
            public void onCancel() { //取消
                MLog.e("自动更新", "下载已取消");
            }
        });
        mDownloadManager.download(uri); //继续下载
    }

    //初始化通知
    public void initNotification(Context context, int progress) {
        notificationManager = ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE));
        NotificationChannel channel;
        if (isBuildAndTargetO(context)) {
            if (notificationManager != null) {
                channel = notificationManager.getNotificationChannel(UPDATE_CHANNEL_ID); // 已经存在就不要再创建了，无法修改通道配置
                if (channel == null) {
                    channel = new NotificationChannel(UPDATE_CHANNEL_ID, UPDATE_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
                    //配置通知通道，无声音
                    channel.setDescription(" no sound");
                    channel.setSound(null, null); //忽略声音
                    channel.setShowBadge(false);
                    channel.enableVibration(false);
                    channel.setVibrationPattern(new long[]{0});
                    notificationManager.createNotificationChannel(channel);
                }
            }
        }
        builder = new NotificationCompat.Builder(context, UPDATE_CHANNEL_ID);
        builder.setContentTitle("下载")
                .setContentText("正在下载更新")
                .setOnlyAlertOnce(true) //设置为true，这样的话，每次只会提醒一次声音，不会重复提醒
                .setAutoCancel(false) // true点击通知后，通知自动消失
                .setWhen(System.currentTimeMillis()) //时间
                .setSmallIcon(R.mipmap.ic_launcher_round); //图标
        builder.setVibrate(new long[]{0});
        builder.setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);//统一消除声音和震动
        downloadProgress(progress);
    }

    public void downloadProgress(int progress) {
        Log.e("update", "downloadProgress: " + progress);
        builder.setProgress(100, progress, false);
        builder.setContentText(progress + "%");
        //下载通知进度提示
        Notification notification = builder.build();
        if (notificationManager != null){
            notificationManager.notify(NOTIFY_ID, notification);
        }
    }

    /**
     * 只有8.0+的机器才能创建NotificationChannel，否则会找不到类。target 8.0+才需要去创建一个channel，否则就用默认通道即null
     */
    private boolean isBuildAndTargetO(Context context) {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O &&
                context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O;
    }

    @Override
    public void onDestroy() {
        isDownLoading = false;
        if (notificationManager != null) {
            notificationManager.cancelAll();
            notificationManager = null;
        }
        super.onDestroy();
    }
}
